package com.example.forum.controller;


import cn.hutool.core.util.IdUtil;
import com.example.forum.commons.annotations.UncheckToken;
import com.example.forum.vo.FileReturn;
import com.example.forum.vo.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.UUID;

/**
 * @author
 * @version 描述：文件上传
 */
@RestController
@Api(tags = "文件上传控制层")
@RequestMapping("/MediaCenter")
public class TMediasController {

    private static final Logger LOGGER = LoggerFactory.getLogger(TMediasController.class);

    @UncheckToken
    @ApiOperation(value = "spring上传文件")
    @RequestMapping(value = "/springUpload", method = {RequestMethod.POST})
    public JsonResult springUpload(HttpServletRequest request) throws IllegalStateException, IOException {
        LOGGER.info("spring上传文件");
        long startTime = System.currentTimeMillis();
        // 将当前上下文初始化给 CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        String savePath = request.getSession().getServletContext().getRealPath("/") + "fileUpload\\";
        String filePathResults = "";
        String fileNameResults = "";
        File saveFileDir = new File(savePath);
        if (!saveFileDir.exists()) {
            // 创建WEB-INF/upload目录
            saveFileDir.mkdirs();
        }
        // 检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {
            // 将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            // 获取multiRequest 中所有的文件名
            Iterator iter = multiRequest.getFileNames();

            while (iter.hasNext()) {
                // 一次遍历所有文件
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                if (file != null) {
                    String path = savePath + file.getOriginalFilename();
                    // 上传
                    file.transferTo(new File(path));
                    if (filePathResults != "") {
                        filePathResults += ",";
                    }

                    filePathResults += "fileUpload/" + file.getOriginalFilename();

                    if (fileNameResults != "") {
                        fileNameResults += ",";
                    }

                    fileNameResults += file.getOriginalFilename();

                }

            }

        }
        long endTime = System.currentTimeMillis();
        System.out.println("Spring方法的运行时间：" + String.valueOf(endTime - startTime) + "ms");

        var fileReturn = new FileReturn();
        fileReturn.FileNames = fileNameResults;
        fileReturn.FileUrls = filePathResults;
        return new JsonResult(HttpStatus.OK, "上传成功", fileReturn);
    }

    @UncheckToken
    @ApiOperation(value = "上传文件方法2")
    @RequestMapping(value = "/fileUpload2", method = {RequestMethod.POST})
    public JsonResult fileUpload2(@RequestParam("file") MultipartFile[] files, HttpServletRequest request)
            throws IOException {
        long startTime = System.currentTimeMillis();
        // System.out.println("fileName："+file.getOriginalFilename());
        String savePath = request.getSession().getServletContext().getRealPath("/") + "fileUpload\\";
        String filePathResults = "";
        String fileNameResults = "";
        File saveFileDir = new File(savePath);
        if (!saveFileDir.exists()) {
            // 创建WEB-INF/upload目录
            saveFileDir.mkdirs();
        }
        for (MultipartFile file : files) {

            String path = savePath + file.getOriginalFilename();

            File newFile = new File(path);
            // 通过CommonsMultipartFile的方法直接写文件（注意这个时候）
            file.transferTo(newFile);
            if (filePathResults != "") {
                filePathResults += ",";
            }

            filePathResults += "fileUpload/" + file.getOriginalFilename();

            if (fileNameResults != "") {
                fileNameResults += ",";
            }

            fileNameResults += file.getOriginalFilename();

        }
        long endTime = System.currentTimeMillis();
        System.out.println("采用file.Transto的运行时间：" + String.valueOf(endTime - startTime) + "ms");
        var fileReturn = new FileReturn();
        fileReturn.FileNames = fileNameResults;
        fileReturn.FileUrls = filePathResults;
        return new JsonResult(HttpStatus.OK, "上传成功", fileReturn);
    }

    @UncheckToken
    @ApiOperation(value = "文件上传流写入")
    @RequestMapping(value = "/fileUpload", method = {RequestMethod.POST})
    public JsonResult fileUpload(@RequestParam("file") MultipartFile[] files, HttpServletRequest request)
            throws IOException {

        // 用来检测程序运行时间
        long startTime = System.currentTimeMillis();
        String savePath = request.getSession().getServletContext().getRealPath("/") + "fileUpload\\";
        String filePathResults = "";
        String fileNameResults = "";
        File saveFileDir = new File(savePath);
        if (!saveFileDir.exists()) {
            // 创建WEB-INF/upload目录
            saveFileDir.mkdirs();
        }

        try {

            for (MultipartFile file : files) {

                // 获取输出流
                OutputStream os = new FileOutputStream(savePath + file.getOriginalFilename());
                // 获取输入流 CommonsMultipartFile 中可以直接得到文件的流
                InputStream is = file.getInputStream();
                int temp;
                // 一个一个字节的读取并写入
                while ((temp = is.read()) != (-1)) {
                    os.write(temp);
                }
                os.flush();
                os.close();
                is.close();

                if (filePathResults != "") {
                    filePathResults += ",";
                }

                filePathResults += "fileUpload/" + file.getOriginalFilename();

                if (fileNameResults != "") {
                    fileNameResults += ",";
                }

                fileNameResults += file.getOriginalFilename();

            }

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("方法一的运行时间：" + String.valueOf(endTime - startTime) + "ms");
        var fileReturn = new FileReturn();
        fileReturn.FileNames = fileNameResults;
        fileReturn.FileUrls = filePathResults;
        return new JsonResult(HttpStatus.OK, "上传成功", fileReturn);
    }

    @UncheckToken
    @ApiOperation(value = "base64文件")
    @RequestMapping(value = "/uploadBase64", method = {RequestMethod.POST})
    @ResponseBody
    public JsonResult base64UpLoad(@RequestParam String base64Data, HttpServletRequest request,
                                   HttpServletResponse response) {
        try {
            String dataPrix = "";
            String data = "";
            if (base64Data == null || "".equals(base64Data)) {
                throw new Exception("上传失败，上传图片数据为空");
            } else {
                String[] d = base64Data.split("base64,");
                if (d != null && d.length == 2) {
                    dataPrix = d[0];
                    data = d[1];
                } else {
                    throw new Exception("上传失败，数据不合法");
                }
            }
            String suffix = "";
            if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)) {// 编码的jpeg图片数据
                suffix = ".jpg";
            } else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {// 编码的icon图片数据
                suffix = ".ico";
            } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {// 编码的gif图片数据
                suffix = ".gif";
            } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {// 编码的png图片数据
                suffix = ".png";
            } else {
                throw new Exception("上传图片格式不合法");
            }
            String tempFileName = UUID.randomUUID().toString() + suffix;

            // 因为BASE64Decoder的jar问题，此处使用spring框架提供的工具包
            byte[] bs = Base64Utils.decodeFromString(data);
            try {
                // 使用apache提供的工具类操作流

                System.out.println(request.getSession().getServletContext().getRealPath("/"));

                String savePath = request.getSession().getServletContext().getRealPath("/") + "fileUpload\\";
                String filePathResults = "";
                String fileNameResults = "";
                File saveFileDir = new File(savePath);
                if (!saveFileDir.exists()) {
                    // 创建WEB-INF/upload目录
                    saveFileDir.mkdirs();
                }

                FileUtils.writeByteArrayToFile(new File(savePath, tempFileName), bs);
            } catch (Exception ee) {
                throw new Exception("上传失败，写入文件失败，" + ee.getMessage());
            }
            return new JsonResult(HttpStatus.OK, "上传成功", "fileUpload/" + tempFileName);
        } catch (Exception e) {
            return new JsonResult(HttpStatus.BAD_REQUEST, "上传失败", null);
        }
    }

    @PostMapping("PostFile")
    public JsonResult postFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        String originalFilename = file.getOriginalFilename();
        String savePath = request.getSession().getServletContext().getRealPath("/") + "Files\\";
        String fileName = IdUtil.randomUUID()+"."+file.getOriginalFilename().split("\\.")[1];
        String filePathResults = "";
        String fileNameResults = "";
        File saveFileDir = new File(savePath);
        if (!saveFileDir.exists()) {
            // 创建WEB-INF/upload目录
            saveFileDir.mkdirs();
        }

        try {
            // 获取输出流
            OutputStream os = new FileOutputStream(savePath + fileName);
            // 获取输入流 CommonsMultipartFile 中可以直接得到文件的流
            InputStream is = file.getInputStream();
            int temp;
            // 一个一个字节的读取并写入
            while ((temp = is.read()) != (-1)) {
                os.write(temp);
            }
            os.flush();
            os.close();
            is.close();
            filePathResults += "/Files/" + fileName;
            fileNameResults += file.getOriginalFilename();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        var fileReturn = new FileReturn();
        fileReturn.FileNames = fileNameResults;
        fileReturn.FileUrls = filePathResults;

        return new JsonResult(HttpStatus.OK, "成功", fileReturn);
    }
}






